import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import React, { useCallback, useState, useImperativeHandle, useMemo, useRef, } from "react";
import { CheckBox, LoadIndicator, ScrollView, SelectBox, } from "devextreme-react";
import Popup from "devextreme-react/popup";
import { CpasIcon, DevPopup } from "~/public/cpas-ui";
import { Addsubject, getAccountInfo, getPresetTopSubject, getSubjectType, } from "./service";
import DataGrid, { Column, Paging } from "devextreme-react/data-grid";
import { Progress } from "antd";
import "./_style.less";
import ReportPopup from "../../ReportPopup";
const FirstLevelSubjectPopup = React.forwardRef((props, ref) => {
    const { AccountDataID, username, dbname, zcbfid } = props;
    const diaParams = useRef();
    const DelteRef = useRef();
    const DataGridRef = useRef();
    const statementProjectRef = useRef();
    const [visible, setVisible] = useState(false);
    const [checkBoxState, setCheckBoxState] = useState(true);
    const [accountYearData, setAccountYearData] = useState([]);
    const [selDefaultValue, setSelDefaultValue] = useState("");
    const [accountYear, setAccountYear] = useState("");
    const Divstyle = {
        display: "flex",
        alignItems: "center",
        justifyContent: "left",
    };
    const Titlestyle = { marginRight: "8px" };
    // const [timeData, setTimeData] = useState<string>('');
    const [firstLevelSubjectData, setFirstLevelSubjectData] = useState([]);
    const [selectedRightData, setSelectedRightData] = useState([]);
    const [subjectLxData, setSubjectLxData] = useState([]);
    const [openVisible111111, setOpenVisible111111] = useState(false);
    // const [reportPopupVisible, setReportPopupVisible] = useState<boolean>(false);
    const [progress, setProgress] = useState(0);
    const [isProgressVisible, setIsProgressVisible] = useState(false);
    const [titlePupopParams, setTitlePupopParams] = useState({
        width: 550,
        height: 220,
        contentText: ["本次新增使用的编号，禁止为空 ！"],
    });
    // const changeTimes = () => {
    //     setTimeData(`${new Date().getTime()}`);
    // }
    const getFetchData = async () => {
        // const auditAdjustId: any = window.localStorage.getItem(`selectDefaultTool_${dbname}`);
        // const tempYear = JSON.parse(auditAdjustId)?.tabledataId ?? sjnd;
        let findTemp = -2;
        const res = await getAccountInfo({ dbname });
        if (res.success) {
            findTemp = res.data.findIndex((item) => {
                return AccountDataID === item.Data_ID;
            });
            // debugger;
            const tempIndex = findTemp >= 0 ? findTemp : 0;
            const DataId = res.data[tempIndex]?.Data_ID;
            const displayNames = res.data[tempIndex]?.displayName;
            res.data.forEach((item, index) => {
                item.index = index;
                return item;
            });
            setAccountYearData(res.data);
            setAccountYear(DataId);
            setSelDefaultValue(displayNames);
            // changeTimes();
        }
    };
    const getListData = async (dataStr) => {
        setOpenVisible111111(true);
        const resLx = await getSubjectType({
            dbname,
            Data_ID: dataStr,
        });
        if (resLx.success) {
            const lx = resLx.data.map((item) => item.type);
            setSubjectLxData(lx);
        }
        else {
            setSubjectLxData([]);
        }
        const res = await getPresetTopSubject({
            dbname,
            Data_ID: dataStr,
            zcbfID: zcbfid,
        });
        if (res.success) {
            setFirstLevelSubjectData(res.data);
            await DataGridRef.current.instance.selectAll();
            setTimeout(() => {
                const dataGridRefScroll = DataGridRef?.current?.instance?.getScrollable();
                if (dataGridRefScroll) {
                    dataGridRefScroll.scrollTo({ left: 0, top: 0 });
                }
                setOpenVisible111111(false);
            }, 500);
        }
    };
    // 自定义方法
    useImperativeHandle(ref, () => ({
        show: (params) => {
            setCheckBoxState(true);
            diaParams.current = params;
            setProgress(0);
            setIsProgressVisible(false);
            getFetchData();
            setVisible(true);
            getListData(params.args.selectYear);
        },
        close: () => {
            setVisible(false);
        },
    }));
    const changeCheck = useCallback((v) => {
        setCheckBoxState(v);
    }, [checkBoxState]);
    // 获取列表的点击项
    // 后期获取list的数据 获取到给tabs进行处理
    const onSelectionChangeds = (e) => {
        getListData(e.selectedItem.Data_ID);
        setAccountYear(e.selectedItem.Data_ID);
        setSelDefaultValue(e.selectedItem.displayName);
    };
    const SavedData = (e) => {
        if (e.changes.length) {
            const { data } = e.changes[0];
            // changetempData(data);
            console.log(data, e.changes, "@@@");
            setFirstLevelSubjectData((old) => {
                const newData = [...old];
                newData.forEach((item) => {
                    if (item.KMBH === data.KMBH) {
                        item.SubjectNo = data.SubjectNo;
                    }
                });
                return newData;
            });
        }
    };
    const bbbbb = async (newData) => {
        // const yearData = newData.data.map((item: any) => item.Data_ID);
        setOpenVisible111111(true);
        const tempA = [];
        for (let index = 0; index < newData.length; index++) {
            const element = newData[index];
            if (element) {
                const res = await Addsubject(element);
                if (res.ok && res.data > 0) {
                    tempA.push(Promise.resolve("ok"));
                }
                else {
                    tempA.push(Promise.resolve(`【(${element.Data_ID})${element.YSKMBH}-${element.KMMC}】${res.data}`));
                }
                const newProgress = Math.floor(((index + 1) / newData.length) * 100);
                setProgress(newProgress);
            }
        }
        Promise.allSettled(tempA)
            .then((results) => {
            console.log(tempA, results, "@@@");
            const falseData = results
                .filter((item1) => item1.value !== "ok")
                .map((item) => item.value);
            if (falseData.length) {
                setTitlePupopParams({
                    width: 700,
                    height: 500,
                    contentText: falseData,
                });
                DelteRef.current.show({
                    title: "失败原因",
                    okCallback: () => {
                        setProgress(0);
                        setIsProgressVisible(false);
                    },
                    onCancel: () => {
                        setProgress(0);
                        setIsProgressVisible(false);
                    },
                });
            }
            else {
                setTitlePupopParams({
                    width: 550,
                    height: 220,
                    contentText: ["增加一级科目成功！"],
                });
                DelteRef.current.show({
                    title: "提示",
                    okCallback: () => {
                        setProgress(0);
                        setIsProgressVisible(false);
                    },
                    onCancel: () => {
                        setProgress(0);
                        setIsProgressVisible(false);
                    },
                });
            }
            setOpenVisible111111(false);
            getListData(accountYear);
            diaParams.current?.okCallback();
        })
            .catch((error) => {
            // 处理错误
            console.error("An error occurred:", error);
        });
    };
    const okBtn = () => {
        DataGridRef.current.instance.saveEditData().then(async () => {
            const res = DataGridRef.current.instance.getSelectedRowsData();
            if (res.length === 0) {
                setTitlePupopParams({
                    width: 550,
                    height: 220,
                    contentText: ["请选择需要添加的科目！"],
                });
                DelteRef.current.show({
                    title: "提示",
                    okCallback: () => { },
                });
                return;
            }
            const reK = res.filter((item) => !item.SubjectNo || !item.SubjectType || !item.SubjectDirection);
            if (reK.length) {
                setTitlePupopParams({
                    width: 550,
                    height: 220,
                    contentText: [
                        "新增一级科目的科目方向、科目类型、本次新增使用的编号，禁止为空 ！",
                    ],
                });
                DelteRef.current.show({
                    title: "提示",
                    okCallback: () => { },
                });
                return;
            }
            setProgress(0);
            setIsProgressVisible(true);
            // console.log(firstLevelSubjectData, res, '@@@');
            let tempData = [];
            res.forEach((items) => {
                const tempObj = {
                    dbname,
                    editUser: username,
                    KMFX: items.SubjectDirection,
                    KMLX: items.SubjectType,
                    itemNames: items.ItemName,
                    YSKMBH: `${items.SubjectNo}`,
                    YSKMMC: items.SubjectName,
                    KMBH: `${items.SubjectNo}~|`,
                    KMMC: items.SubjectName,
                    PKMBH: "",
                    JC: 1,
                };
                tempData.push(tempObj);
            });
            let saveData = [];
            if (checkBoxState) {
                accountYearData.forEach((year) => {
                    let newDataArray = tempData.map((items) => {
                        return { ...items, Data_ID: year.Data_ID };
                    });
                    saveData = saveData.concat(newDataArray);
                });
            }
            else {
                tempData.forEach((items) => {
                    let newDataObject = { ...items, Data_ID: accountYear };
                    saveData.push(newDataObject);
                });
            }
            await bbbbb(saveData);
            return;
        });
    };
    const onSelectionChangedRight = useCallback(({ selectedRowKeys }) => {
        setSelectedRightData(selectedRowKeys);
    }, []);
    const changeItemName = (rowData, isClear, itemData = {}) => {
        setFirstLevelSubjectData((old) => {
            const newData = [...old];
            if (isClear) {
                newData.forEach((item) => {
                    if (item.KMBH === rowData.KMBH) {
                        item.ItemName = null;
                        item.ItemNo = null;
                    }
                });
            }
            else {
                newData.forEach((item) => {
                    if (item.KMBH === rowData.KMBH) {
                        item.ItemName = itemData.ItemName;
                        item.ItemNo = itemData.ItemNo;
                    }
                });
            }
            return newData;
        });
    };
    const cancelFun = () => {
        if (!openVisible111111) {
            setVisible(false);
        }
    };
    return (_jsxs(_Fragment, { children: [_jsxs(Popup, { ref: ref, visible: visible, title: diaParams.current?.args?.title, width: 1000, height: 700, onHiding: () => cancelFun(), className: "FirstLevelSubjectCalss", style: { overflow: "unset" }, toolbarItems: [
                    {
                        widget: "dxButton",
                        toolbar: "bottom",
                        location: "after",
                        options: {
                            text: "取消",
                            onClick: () => cancelFun(),
                        },
                    },
                    {
                        widget: "dxButton",
                        toolbar: "bottom",
                        location: "after",
                        options: {
                            text: "确定",
                            type: "default",
                            onClick: () => okBtn(),
                        },
                    },
                ], 
                // dragOutsideBoundary={true}
                resizeEnabled: true, children: [openVisible111111 && (_jsx("div", { style: {
                            position: "absolute",
                            width: "960px",
                            height: "625px",
                            display: "flex",
                            alignItems: "center",
                            justifyContent: "center",
                            opacity: 0.5,
                            zIndex: "99999",
                            background: "#ddd",
                        }, children: _jsx(LoadIndicator, { id: "medium-indicator", height: 50, width: 50 }) })), _jsxs("div", { style: { width: "100%", height: "100%" }, children: [_jsx("div", { style: { marginBottom: "15px" }, children: useMemo(() => {
                                    if (selDefaultValue) {
                                        return (_jsxs("div", { style: Divstyle, children: [_jsx("div", { style: Titlestyle, children: "\u8D26\u5957:" }), _jsx(SelectBox, { width: 200, dataSource: accountYearData, displayExpr: "displayName", valueExpr: "displayName", value: selDefaultValue, onSelectionChanged: onSelectionChangeds, dropDownOptions: {
                                                        width: "350px",
                                                    } })] }));
                                    }
                                    return _jsx("div", { style: { height: "32px" }, children: "loading..." });
                                }, [selDefaultValue]) }), _jsxs("div", { style: { height: "calc(100% - 50px)" }, children: [_jsxs(DataGrid
                                    // width={650}
                                    , { 
                                        // width={650}
                                        ref: DataGridRef, height: "100%", className: "PaperDevSortableGrid devHeadersCenter", dataSource: firstLevelSubjectData, keyExpr: "KMBH", hoverStateEnabled: true, showBorders: true, showColumnLines: false, 
                                        // 显示行的线
                                        showRowLines: true, allowColumnResizing: false, onSaved: SavedData, selectedRowKeys: selectedRightData, selection: {
                                            mode: "multiple",
                                            selectAllMode: "allPages",
                                            showCheckBoxesMode: "always",
                                        }, onSelectionChanged: onSelectionChangedRight, 
                                        // scrolling={{
                                        //     mode: "virtual",
                                        //     rowRenderingMode: "virtual",
                                        //     renderAsync: true
                                        // }}
                                        editing: {
                                            mode: "cell",
                                            startEditAction: "click",
                                            allowUpdating: true,
                                        }, children: [_jsx(Paging, { enabled: false }), _jsx(Column, { caption: "\u63A8\u8350\u79D1\u76EE\u7F16\u53F7", allowEditing: false, width: 120, dataField: "KMBH", alignment: "left" }), _jsx(Column, { caption: "\u79D1\u76EE\u540D\u79F0", allowEditing: false, width: 200, dataField: "SubjectName", alignment: "left" }), _jsx(Column, { caption: "\u79D1\u76EE\u65B9\u5411", width: 90, dataField: "SubjectDirection", alignment: "left", lookup: {
                                                    dataSource: ["借", "贷"],
                                                    searchEnabled: true,
                                                } }), _jsx(Column, { caption: "\u79D1\u76EE\u7C7B\u578B", width: 90, dataField: "SubjectType", alignment: "left", lookup: {
                                                    dataSource: subjectLxData,
                                                    searchEnabled: true,
                                                } }), _jsx(Column, { caption: "\u672C\u6B21\u65B0\u589E\u4F7F\u7528\u7684\u7F16\u53F7", dataField: "SubjectNo", dataType: "number", alignment: "left" }), _jsx(Column, { caption: "\u5BF9\u5E94\u7684\u62A5\u8868\u9879\u76EE", width: 300, dataField: "ItemName", alignment: "left", allowEditing: false, cellRender: (cell) => {
                                                    let tempItemName = "";
                                                    if (cell.data.ItemName) {
                                                        tempItemName = cell.data.ItemName;
                                                    }
                                                    return (_jsx(_Fragment, { children: _jsxs("div", { style: {
                                                                display: "flex",
                                                                alignItems: "center",
                                                                justifyContent: "space-between",
                                                                paddingRight: "16px",
                                                            }, children: [_jsx("div", { style: {
                                                                        width: "249px",
                                                                        padding: "0 1px",
                                                                        overflow: "hidden",
                                                                        textOverflow: "ellipsis",
                                                                        whiteSpace: "nowrap",
                                                                    }, title: tempItemName, children: tempItemName }), _jsxs("div", { style: { width: "40px" }, children: [_jsx(CpasIcon, { type: "icon-ellipsis", onClick: () => {
                                                                                // changeGetFiltration(cell.data);
                                                                                statementProjectRef.current.show({
                                                                                    title: "选择报表项目",
                                                                                    dbname: dbname,
                                                                                    Data_ID: accountYear,
                                                                                    ownerReport: "",
                                                                                    selectMode: "1",
                                                                                    // 选择 模式 0：单选 1：多选连机选择
                                                                                    okCallback: (r) => {
                                                                                        // console.log(r, '@@@');
                                                                                        const res = r
                                                                                            .map((item) => {
                                                                                            return item.itemName;
                                                                                        })
                                                                                            .join(",");
                                                                                        const resNo = r
                                                                                            .map((item) => {
                                                                                            return item.code;
                                                                                        })
                                                                                            .join(",");
                                                                                        changeItemName(cell.data, false, {
                                                                                            ItemName: res,
                                                                                            ItemNo: resNo,
                                                                                        });
                                                                                        // setSelectedYears(res);
                                                                                    },
                                                                                });
                                                                            } }), _jsx("span", { style: { marginLeft: "8px" }, children: _jsx(CpasIcon, { type: "icon-close1", onClick: () => {
                                                                                    console.log("清空11", "@@@");
                                                                                    changeItemName(cell.data, true);
                                                                                } }) })] })] }) }));
                                                } })] }), _jsxs("div", { style: {
                                            position: "absolute",
                                            bottom: "30px",
                                            left: "15px",
                                            zIndex: "99",
                                            display: "flex",
                                            alignItems: "center",
                                            width: "400px",
                                        }, children: [_jsxs("div", { style: {
                                                    marginRight: "8px",
                                                    display: "flex",
                                                    alignItems: "center",
                                                }, children: [_jsx("span", { style: {
                                                            marginLeft: "8px",
                                                            marginRight: "10px",
                                                            whiteSpace: "nowrap",
                                                        }, children: "\u662F\u5426\u589E\u52A0\u591A\u5E74\u5EA6:" }), _jsx(CheckBox, { value: checkBoxState, onValueChange: (e) => {
                                                            changeCheck(e);
                                                        } })] }), isProgressVisible && (_jsx(Progress, { strokeColor: {
                                                    "0%": "#108ee9",
                                                    "100%": "#87d068",
                                                }, percent: progress }))] })] })] })] }), _jsx(DevPopup.Default, { ref: DelteRef, width: titlePupopParams.width, height: titlePupopParams.height, children: () => {
                    return (_jsx(ScrollView, { width: "100%", height: `${titlePupopParams.height - 130}px`, children: _jsx("div", { children: titlePupopParams.contentText.map((item) => {
                                return _jsx("div", { children: item });
                            }) }) }));
                } }), _jsx(ReportPopup, { ref: statementProjectRef })] }));
});
export default FirstLevelSubjectPopup;
